package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.Header;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.adapter.EmptyAdapter;
import com.xindaoapp.happypet.adapter.MyCollectListAdapter2;
import com.xindaoapp.happypet.adapter.MyCollectListAdapter2.OnNextPageListener;
import com.xindaoapp.happypet.adapter.XinDaoBaseAdapter.ILoadNextPageData;
import com.xindaoapp.happypet.api.AddClient;
import com.xindaoapp.happypet.api.Address;
import com.xindaoapp.happypet.bean.Message;
import com.xindaoapp.happypet.bean.MyHuiFu;
import com.xindaoapp.happypet.utils.CommonParameter.UserState;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;

/**
 * 我的收藏列表
 * 
 * @author Stone
 * 
 */
public class MyCollectListActivity extends BaseActivity {

    private final LinkedList<Message> arrays = new LinkedList<Message>();
    private String total;
    private boolean isFirst = true;
    private MyCollectListAdapter2 adapter;
    private PullToRefreshListView myshoucang_list;
    private RelativeLayout noresult;
    private ReceiveForDelete mReceive;
    private Message mMessage;
    private int mPosition;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }



    @Override
    protected void initViews() {
        super.initViews();

        mReceive = new ReceiveForDelete();
        registerReceiver(mReceive, new IntentFilter(Constants.ACTION_CANCEL_COLLECT));

        myshoucang_list = (PullToRefreshListView) this.findViewById(R.id.listview);
        noresult = (RelativeLayout) this.findViewById(R.id.no_data);



        myshoucang_list = (PullToRefreshListView) this.findViewById(R.id.listview);
        myshoucang_list.setMode(Mode.PULL_FROM_START);

        View sreachHeader =
                View.inflate(MyCollectListActivity.this, R.layout.item_searchview, null);
        btn_search = (Button) sreachHeader.findViewById(R.id.iv_shop_search);
        et_search = (EditText) sreachHeader.findViewById(R.id.et_search);
        myshoucang_list.getRefreshableView().addHeaderView(sreachHeader);
        myshoucang_list.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                et_search.getText().clear();
                onLoadDatas();
            }
        });
        // myshoucang_list.getRefreshableView().setOnItemClickListener(new OnItemClickListener() {
        //
        // @Override
        // public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
        //
        // Intent intent = new Intent(MyCollectListActivity.this, PostDetailActivity.class);
        // mMessage = (Message) parent.getAdapter().getItem(position);
        // mPosition = position - 1;
        // intent.putExtra(Constants.KEY_POST_TID, mMessage.getTid());
        // startActivity(intent);
        // }
        // });
    }

    @Override
    protected void initEvents() {
        btn_search.setOnClickListener(mOnClickListener);
    }


    private final OnClickListener mOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.iv_shop_search:// 搜索
                    hideKeyBoard();
                    searchCollection();
                    break;
            }
        }

        /**
         * 搜索搜藏的帖子
         */
        private void searchCollection() {
            String searctText = et_search.getText().toString().trim();
            if (TextUtils.isEmpty(searctText)) {
                Toast.makeText(MyCollectListActivity.this, "请输入关键字", Toast.LENGTH_SHORT).show();
                return;
            }
            getMoccaApi().getSearchCollection(searctText, new IRequest<List<Message>>() {

                private List<Message> array;

                @Override
                public void request(List<Message> t) {
                    array = t;
                    if (array != null && array.size() > 0) {
                        arrays.clear();
                        arrays.addAll(array);

                        if (array != null && array.size() > 0) {
                            array.clear();
                        }
                        adapter =
                                new MyCollectListAdapter2(MyCollectListActivity.this, arrays,
                                        Constants.PAGE_SIZE, R.layout.activity_mycollect_item,
                                        R.layout.item_loading);
                        adapter.setOnNextPageListener(onNextPageListener);
                        myshoucang_list.getRefreshableView().setAdapter(adapter);
                    } else {
                        myshoucang_list.getRefreshableView().setAdapter(
                                new EmptyAdapter(MyCollectListActivity.this));
                    }

                }
            });
        }
    };


    @Override
    protected void onLoadDatas() {
        super.onLoadDatas();
        getData();
    }



    private void getData() {
        // TODO Auto-generated method stub
        RequestParams params = new RequestParams();
        params.put("uid", UserState.getUserUid());
        params.put("page", "1");
        params.put("pagesize", Address.PAGESIZE);
        AddClient.post(Address.FAVORITE, params, new AsyncHttpResponseHandler() {
            private List<Message> array;

            @Override
            public void onSuccess(int statusCode, Header[] headers, String content) {
                try {
                    isFirst = false;
                    onDataArrived(true);
                    MyHuiFu huifu = JSON.parseObject(content, MyHuiFu.class);
                    total = huifu.getTotal();
                    array = huifu.getArray();
                    if (array.size() > 0) {
                        arrays.clear();
                        arrays.addAll(array);
                    } else {
                        onDataArrivedEmpty();
                    }
                    if (array != null && array.size() > 0) {
                        array.clear();
                    }
                    adapter =
                            new MyCollectListAdapter2(MyCollectListActivity.this, arrays,
                                    Constants.PAGE_SIZE, R.layout.activity_mycollect_item,
                                    R.layout.item_loading);
                    adapter.setOnNextPageListener(onNextPageListener);
                    myshoucang_list.getRefreshableView().setAdapter(adapter);

                    if (total.equals("0")) {
                        myshoucang_list.setVisibility(View.GONE);
                        noresult.setVisibility(View.VISIBLE);
                    }

                    myshoucang_list.onRefreshComplete();


                } catch (Exception e) {
                    e.printStackTrace();
                }
                super.onSuccess(statusCode, content);
            }

            @Override
            public void onFailure(Throwable error, String content) {
                myshoucang_list.onRefreshComplete();

                if (isFirst) {
                    onDataArrived(false);
                } else {
                    onDataArrived(true);
                }
                super.onFailure(error, content);
            }
        });

    }

    @Override
    protected int getContentViewResId() {
        return R.layout.activity_my_collect_list;
    }

    @Override
    protected OnClickListener getLeftViewClickListener() {
        return new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                finish();
            }
        };
    }


    @Override
    protected int getTopBarLeftImageViewRes() {
        return R.drawable.top_bar_back;
    }


    @Override
    protected String getTopBarTitleStrRes() {
        return "我的收藏";
    }


    /**
     * 加載下一頁的方法
     */
    private final OnNextPageListener onNextPageListener = new OnNextPageListener() {

        @Override
        public void nextPage(int start, int size, final ILoadNextPageData<Message> iLoadNextPageData) {
            RequestParams params = new RequestParams();
            params.put("uid", UserState.getUserUid());
            params.put("page", String.valueOf(start));
            params.put("pagesize", String.valueOf(size));
            AddClient.post(Address.FAVORITE, params, new AsyncHttpResponseHandler() {
                private List<Message> array;

                @Override
                public void onSuccess(int statusCode, Header[] headers, String content) {


                    MyHuiFu huifu = JSON.parseObject(content, MyHuiFu.class);
                    total = huifu.getTotal();
                    array = huifu.getArray();
                    if (array == null) {
                        return;
                    }
                    if (array != null && array.size() > 0) {
                        List<Message> message = new ArrayList<Message>();
                        message.addAll(array);
                        iLoadNextPageData.loadNextPageData(message);
                    }
                }

            });
        }
    };
    private Button btn_search;
    private EditText et_search;



    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mReceive);
    }


    class ReceiveForDelete extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            String is = intent.getStringExtra("isCollect");
            if (is.equals("ok")) {
                arrays.add(mPosition, mMessage);
            } else {
                arrays.remove(mMessage);
            }
            adapter.notifyDataSetChanged();
        }
    }



}
